<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            var coinChange = function (coins, amount) {
                let bagSize = amount
                let dp = new Array(bagSize + 1).fill(Infinity)
                //当背包容量为0时，最少的物品个数自然是0。至于为什么初始化为Infinite，是因为Math.min要比较最小值
                //不能直接初始化-1，就是因为min要比较最小值，如果装不满或者溢出，那么结果就是Infinite。
                dp[0] = 0
                for (let i = 0; i < coins.length; i++) {
                    for (let j = coins[i]; j <= bagSize; j++) {
                        dp[j] = Math.min(dp[j], dp[j - coins[i]] + 1)
                    }
                }
                return dp[bagSize] == Infinity ? -1 : dp[bagSize]
            }
            coinChange([1, 2, 5], 11)
        </script>
    </body>
</html>
